import logging
#用于元素定位的封装
#driver驱动程序，定位xpath
def wait_element_by_xpath(driver,child_xpath ,click=False,timeout =60):
    try:
        #显示等待,find_element_by_xpath(name)需要检查   By是common.by
        element =WebDriverWait(driver,timeout).until(lambda x:x.find_element(By.XPTAH,child_xpath))
        #另外1个写法
        #element =WebDriverWait(driver,timeout).until(lambda x:x.find_element_by_xpath(child_xpath))
        print "loaded"
        #封装了click()
        if click:
            element.click()
            return True
        else:
            return element
    except (TimeoutException, NoSuchElementException), e:
        print "[wait_element_by_xpath : %s] Exception : [%s]" % (child_xpath, e)
        return False

#定位toast -2017.12.21
def find_toast(driver,timeout,poll_frequency, message):
    try:
        message = '//*[@text=\'{}\']'.format(message)
        
        element = WebDriverWait(driver,timeout,poll_frequency).until(ec.presence_of_element_located((By.XPATH, message)))
        _logger.debug("Get Toast : [%s]" % element)
        return element.get_attribute('text')
    except (TimeoutException, NoSuchElementException) as e:
        _logger.debug("Get Toast : [%s and %s]" % (message, e))
        return False
#业务那边这样写的find_toast(driver, 10,0.2'you have pushed the setExtra Button!') 但是在desirecaps里面指定uiautomator2，发现就无法运行了。


#定位class
def wait_elements_by_class(driver, name, timeout=120):
    try:
        elements = WebDriverWait(driver, timeout).until(lambda x: x.find_elements_by_class_name(name))
        return elements
    except (TimeoutException, NoSuchElementException) as e:
        _logger.warning("wait_element_by_name : %s Exception : %s" % (name, e))
        return False

#定义单个元素
def wait_element_by_id(driver, id, click=False, timeout=10,firstName='xxxxxx/'):
    try:
        element = WebDriverWait(driver, timeout).until(lambda s: s.find_element(By.ID, firstName + id))
        if click:
            element.click()
        return element
    except (TimeoutException, NoSuchElementException) as e:
        _logger.info('[wait_element_by_id : %s] Exception : [%s]' % (id, e))
        return False

#定义多个元素
def wait_elements_by_id(driver, id, timeout=10,firstName='xxxxx/'):
    try:
        elements = WebDriverWait(driver, timeout).until(lambda s: s.find_elements(By.ID, 10,firstName+ id))
        return elements
    except (TimeoutException, NoSuchElementException) as e:
        _logger.info('[wait_elements_by_id : %s] Exception : [%s]' % (id, e))
        return False

#定位name appium1.5以上已经弃用
def wait_element_by_name(driver, name, click=False, timeout=60):
    try:
        element = WebDriverWait(driver, timeout).until(lambda x: x.find_element_by_name(name))
        if click:
            element.click()
            return True
        else:
            return element
    except (TimeoutException, NoSuchElementException), e:
        print "[wait_element_by_name : %s] Exception : [%s]" % (name, e)
        return False

#移动坐标
def swipe_element(driver, start, end):
    start_btn = wait_element_by_id(driver, start)
    end_btn = wait_element_by_id(driver, end)
    driver.swipe(start_btn.location['x'], start_btn.location['y'], end_btn.location['x'], end_btn.location['y'])



#智能等待
def find_toast(deriver,message):
    try:
        # presence_of_element_located：判断一个元素是否存在于页面的DOM中
        #休眠间隔为10秒
        element = WebDriverWait(driver,10).until(ec.presence_of_element_located((By.PARTIAL_LINK_TEXT, message)))
        _logger.debug("Get Toast : [%s]" % element)
        return True
    except Exception, e:
        _logger.debug("Get Toast: [%s and %s]" % (element,e))
        return False
        
#滑动到一排按钮的指定按钮上
def get_element(self, driver, name):
        element = 0
        while not element:
            time.sleep(1)
            elements = self.wait_elements_by_className(driver, 'android.widget.Button')
            e_start = config.buttons[elements[0].text]
            e_end = config.buttons[elements[-1].text]
            e_index = config.buttons[name]
            if e_start <= e_index <= e_end:
                index = e_index - e_start
                element = elements[index]
            elif e_index < e_start:
                self.swipe_element(driver, elements[1], elements[2])
            else:
                self.swipe_element(driver, elements[-1], elements[-2])
        return element